package org.jeecg.modules.appuser.job;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.Date.DateUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.entity.*;
import org.jeecg.modules.appuser.service.*;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 20 点关闭任务，开始抽奖
 */
@Slf4j
public class CloseLuckDrawTask implements Job {

    @Autowired
    private ITbUserLuckdrawService tbUserLuckdrawService;


    @Autowired
    private ITbUserLuckdrawDetailService tbUserLuckdrawDetailService;

    @Autowired
    private ITbUserWalletService tbUserWalletService;

    @Autowired
    private ITbUserWalletDetailService tbUserWalletDetailService;

    @Autowired
    private ITbUserNoticeService tbUserNoticeService;
    @Autowired
    private ITbMnUserService tbMnUserService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("开始抽奖,dateTime:{}", DateUtils.now());

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state", 1);
        queryWrapper.eq("luckdraw_type", 1);//每日抽奖
        TbUserLuckdraw tbUserLuckdraw = tbUserLuckdrawService.getOne(queryWrapper);
        if (null != tbUserLuckdraw) {
            QueryWrapper bUserLuckdrawDetailQueryWrapper = new QueryWrapper();
            bUserLuckdrawDetailQueryWrapper.eq("luckdraw_id", tbUserLuckdraw.getId());
            List<TbUserLuckdrawDetail> tbUserLuckdrawDetailList = tbUserLuckdrawDetailService.list();
            if (null != tbUserLuckdrawDetailList && tbUserLuckdrawDetailList.size() > 0) {
                //抽奖人数
                int person_number = tbUserLuckdrawDetailList.size();
                int random_number = getRandom(person_number);
                TbUserLuckdrawDetail tbUserLuckdrawDetail = tbUserLuckdrawDetailList.get(random_number - 1);
                String user_id = tbUserLuckdrawDetail.getUserId();
                tbUserLuckdraw.setLuckUserId(user_id);
                //设置为听状态
                tbUserLuckdraw.setState(0);
                tbUserLuckdraw.setReleaseStatus(0);   //释放
                if (tbUserLuckdrawService.updateById(tbUserLuckdraw)) {
                    releaseLuckdraw(tbUserLuckdraw, user_id);

                    addMsgNotice(tbUserLuckdraw, user_id);
                    log.info("抽奖成功，等待下轮抽奖,dateTime:{}", DateUtils.now());
                }
            }else{
                tbUserLuckdraw.setState(0);
                tbUserLuckdraw.setReleaseStatus(0);   //释放
                if (tbUserLuckdrawService.updateById(tbUserLuckdraw)) {
                    log.info("开始抽奖,dateTime:{}", DateUtils.now());
                }
            }
        }

        log.info("开始抽奖,dateTime:{}", DateUtils.now());

    }

    //增加消息通知
    private void addMsgNotice(TbUserLuckdraw tbUserLuckdraw, String user_id) {
        TbUserNotice tbUserNotice=new TbUserNotice();
        TbMnUser tbMnUser= tbMnUserService.getById(user_id);
        tbUserNotice.setNoticeContent("抽奖完成，恭喜"+tbMnUser.getPhone()+"获得"+ tbUserLuckdraw.getBalance()+tbUserLuckdraw.getRewardContent());
        tbUserNotice.setNoticeTitle(tbUserLuckdraw.getStartTime()+ "抽奖结果");
        tbUserNotice.setNoticeSendStatus("0");
        tbUserNotice.setNoticeType("2");
        tbUserNoticeService.addUserNotice(tbUserNotice);
    }

    /**
     * 释放中奖结果
     *
     * @param tbUserLuckdraw
     * @param user_id
     */
    private void releaseLuckdraw(TbUserLuckdraw tbUserLuckdraw, String user_id) {
        TbUserWallet tbUserWallet = tbUserWalletService.getOneByUser_id(user_id);
        if (null != tbUserWallet) {
            synchronized (tbUserWallet) {
                BigDecimal balance = tbUserWallet.getBalance();
                BigDecimal reward_balance = tbUserLuckdraw.getBalance();
                BigDecimal new_balance = balance.add(reward_balance);
                tbUserWallet.setBalance(new_balance);
                tbUserWalletService.updateById(tbUserWallet);
                TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
                tbUserWalletDetail.setUserId(user_id);
                tbUserWalletDetail.setWalletId(tbUserWallet.getId());
                tbUserWalletDetail.setPayFrom(PayTypeConstant.PAYFORM_LUCKDRAW);
                tbUserWalletDetail.setPayNumber(reward_balance);
                tbUserWalletDetail.setPayType(PayTypeConstant.PAYTYPE_INCOME);
                tbUserWalletDetail.setBalance(new_balance);
                if (tbUserWalletDetailService.save(tbUserWalletDetail)) {
                    log.info("中奖  已经发放");
                }
            }
        }
    }

    public static int getRandom(int max) {

        int min = 1;
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;
    }

}
